﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
using System.Web;
using WmsService.Derived;
using WmsService.Exceptions;
using WmsService.Generate;
using WmsService.In;
using WmsService.Out;
using WmsService.Security;
using WmsService.Util;

namespace WmsService
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public partial class Service : ServiceBase,IService
    {

        #region Customer
        public List<Customer> GetCustomers()
        {
            try
            {
                SecurityValidate();
                var entity = Factory.ContextFactory.Create();
                var q = from c in entity.Customer
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<Customer> GetCustomersByCondition(string condition)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<Customer>("select * from  dbo.Customer where  1=1 " + condition).ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public Customer GetCustomer(string ownerNo)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.Customer
                        where c.OWNERNO == ownerNo
                        select c;

                var customer = q.FirstOrDefault();
                if(customer != null)
                {
                    ctx.Detach(customer);
                    return customer;
                }
                return null;
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveCustomers(List<Customer> list)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();

                foreach (var customer in list)
                {
                    if (customer.WcfEntityState == EntityState.Modified)
                    {
                        customer.UPDATETIME = DateTime.Now;
                        customer.UPDATERNAME = ContextUserID;
                    }
                    else if (customer.WcfEntityState == EntityState.Added)
                    {
                        customer.CREATERNAME = ContextUserID;
                        customer.UPDATETIME = DateTime.Now;
                        customer.UPDATERNAME = ContextUserID;
                        customer.CREATETIME = DateTime.Now;
                    }
                    ctx.AddToCustomer(customer);
                    ctx.ObjectStateManager.ChangeObjectState(customer, customer.WcfEntityState);
                }
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }
        }

        public void DeleteCustomer(string ownerNo)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var customer = GetCustomer(ownerNo);
                if(customer == null)
                {
                    ExceptionHandler.ThrowException("不存在供应商代码：" + ownerNo);
                }
                var list = this.GetInStoreBillsByCondition(string.Format(" and ProviderCode='{0}' ", ownerNo));
                if (list.Count > 0)
                {
                    ExceptionHandler.ThrowException("该供应商已经在使用中：" + ownerNo);
                }
                ctx.AddToCustomer(customer);
                ctx.ObjectStateManager.ChangeObjectState(customer, EntityState.Deleted);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }
        }

        #endregion

        #region SystemUser
        public List<SystemUser> GetSystemUsers()
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.SystemUser
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveSystemUsers(List<SystemUser> list)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();

                foreach (var user in list)
                {
                    if (user.WcfEntityState == EntityState.Modified)
                    {
                        user.UPDATETIME = DateTime.Now;
                    }
                    else if (user.WcfEntityState == EntityState.Added)
                    {
                        user.UPDATETIME = DateTime.Now;
                        user.CREATETIME = DateTime.Now;
                    }
                    ctx.AddToSystemUser(user);
                    ctx.ObjectStateManager.ChangeObjectState(user, user.WcfEntityState);
                }
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }
        }
        #endregion

        #region GoodsCodeType
        public List<GoodsCodeType> GetGoodsCodeTypes()
        {
            try
            {
                //SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.GoodsCodeType
                        where ( String.IsNullOrEmpty(c.ExtVarChar3) || c.ExtVarChar3 =="1")
                        select c;
                var list =  q.ToList();
                return list;
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<GoodsCodeType> GetGoodsCodeTypesByCondition(string condition)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<GoodsCodeType>("select * from  dbo.GoodsCodeType where  1=1 " + condition).ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveGoodsCodeTypes(List<GoodsCodeType> list)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();

                foreach (var goodsCodeType in list)
                {
                    if(goodsCodeType.WcfEntityState == EntityState.Modified)
                    {
                        string condition = " and  NewGoodsCode='{0}'";
                        condition = string.Format(condition, goodsCodeType.NewGoodsCode);
                        var storeGoodsList = this.GetStoreGoodsListByCondition(condition);
                        foreach (var storeGoods in storeGoodsList)
                        {
                            if(storeGoods.NewGoodsName != goodsCodeType.NewGoodsName
                                ||storeGoods.OldGoodsCode != goodsCodeType.OldGoodsCode )
                            {
                                storeGoods.NewGoodsName = goodsCodeType.NewGoodsName;
                                storeGoods.OldGoodsCode = goodsCodeType.OldGoodsCode;

                                ctx.AddToStoreGoods(storeGoods);
                                ctx.ObjectStateManager.ChangeObjectState(storeGoods, EntityState.Modified);
                            }
                        }
                    }
                    ctx.AddToGoodsCodeType(goodsCodeType);
                    ctx.ObjectStateManager.ChangeObjectState(goodsCodeType, goodsCodeType.WcfEntityState);
                }
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }

        }

        public void AddOrValidateGoodsCodeType(GoodsCodeType goodsCodeType)
        {
            var ctx = Factory.ContextFactory.Create();
            var q = from c in ctx.GoodsCodeType
                    where c.NewGoodsCode == goodsCodeType.NewGoodsCode
                    select c;
            if(q.FirstOrDefault() == null)
            {
                ctx.AddToGoodsCodeType(goodsCodeType);
                ctx.ObjectStateManager.ChangeObjectState(goodsCodeType, EntityState.Added);
                ctx.SaveChanges();
            }
            
        }

        public void DeleteGoodsCodeType(GoodsCodeType goodsCodeType)
        {
            //首先找入库单，再找库存，再找出库单，如果都不存在，则可以删除
            var ctx = Factory.ContextFactory.Create();
            var q = from c in ctx.InStoreBillDtl
                    where c.NewGoodsCode == goodsCodeType.NewGoodsCode
                    select c;
            if(q.FirstOrDefault() != null)
            {
                ExceptionHandler.ThrowException("该物料代码已经在入库明细中使用，不能删除！" + goodsCodeType.NewGoodsCode);
            }

            var q2 = from c in ctx.StoreGoods
                where c.NewGoodsCode == goodsCodeType.NewGoodsCode
                select c;
            var storeGoods = q2.FirstOrDefault();
            if (storeGoods != null)
            {
                ctx.Detach(storeGoods);
                if (storeGoods.Quantity != 0)
                {
                    ExceptionHandler.ThrowException("该物料代码已经在库存中使用，不能删除！\n\r如需删除该物料代码，请先出库，将该物料全部出完，只要数量为0，即可删除。" +
                                                    goodsCodeType.NewGoodsCode);
                }
                else
                {
                    ctx.AddToStoreGoods(storeGoods);
                    ctx.ObjectStateManager.ChangeObjectState(storeGoods, EntityState.Deleted);
                }
            }
            ctx.AddToGoodsCodeType(goodsCodeType);
            ctx.ObjectStateManager.ChangeObjectState(goodsCodeType, EntityState.Deleted);
            ctx.SaveChanges();
        }


        public GoodsCodeType CancelGoodsCodeType(GoodsCodeType goodsCodeType)
        {
            var ctx = Factory.ContextFactory.Create();
            var q2 = from c in ctx.GoodsCodeType
                     where c.NewGoodsCode == goodsCodeType.NewGoodsCode
                     select c;
            var codeType = q2.FirstOrDefault();
            if (codeType != null)
            {
                if(codeType.ExtVarChar3 == "0")
                {
                    ExceptionHandler.ThrowException("该物料代码已经作废！" +goodsCodeType.NewGoodsCode);
                }
                codeType.ExtVarChar3 = "0";
                ctx.Detach(codeType);
                ctx.AddToGoodsCodeType(codeType);
                ctx.ObjectStateManager.ChangeObjectState(codeType, EntityState.Modified);
                ctx.SaveChanges();
                return codeType;
            }
            ExceptionHandler.ThrowException("该物料代码不存在！" + goodsCodeType.NewGoodsCode);
            return null;
        }

        public GoodsCodeType UnCancelGoodsCodeType(GoodsCodeType goodsCodeType)
        {
            var ctx = Factory.ContextFactory.Create();
            var q2 = from c in ctx.GoodsCodeType
                     where c.NewGoodsCode == goodsCodeType.NewGoodsCode
                     select c;
            var codeType = q2.FirstOrDefault();
            if (codeType != null)
            {
                if (codeType.ExtVarChar3 != "0")
                {
                    ExceptionHandler.ThrowException("该物料代码并没有作废，不能取消作废！" + goodsCodeType.NewGoodsCode);
                }
                codeType.ExtVarChar3 = "1";
                ctx.Detach(codeType);
                ctx.AddToGoodsCodeType(codeType);
                ctx.ObjectStateManager.ChangeObjectState(codeType, EntityState.Modified);
                ctx.SaveChanges();
                return codeType;
            }
            ExceptionHandler.ThrowException("该物料代码不存在！" + goodsCodeType.NewGoodsCode);
            return null;
        }

        #endregion

        #region InStoreBill
        public List<InStoreBill> GetInStoreBills()
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.InStoreBill
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<InStoreBill> GetInStoreBillsByCondition(string condition)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<InStoreBill>("select * from  dbo.InStoreBill where  1=1 " + condition + "   order by BillID,InBillDate").ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveInStoreBills(List<InStoreBill> list)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region InStoreBillDtl
        public List<InStoreBillDtl> GetInStoreBillDtls()
        {
            try
            {
                //SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.InStoreBillDtl
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public InStoreBillDtl GetInStoreBillDtl(string inStoreBillDtlID)
        {
            try
            {
                //SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.InStoreBillDtl
                        where c.BillDtlID == inStoreBillDtlID
                        select c;
                return q.FirstOrDefault();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<InStoreBillDtl> GetInStoreBillDtlsByCondition(string condition)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<InStoreBillDtl>("select * from  dbo.InStoreBillDtl where  1=1 " + condition + "  order by BillID,Idx ").ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveInStoreBillDtls(List<InStoreBillDtl> list)
        {
            throw new NotImplementedException();
        }



        public void DeleteInStoreBillDtl(InStoreBillDtl dtl)
        {
            try
            {
                SecurityValidate(); 
                var ctx = Factory.ContextFactory.Create();
                //增加校验，如果入库单为草稿可以删除，否则不可以。
                //增加校验，如果该入库单明细已经分摊了发票，则也不可以删除
                var q1 = from m in ctx.InStoreBill
                         where m.BillID == dtl.BillID
                         select m;
                var inStoreBill = q1.FirstOrDefault();
                if(inStoreBill == null)
                {
                    ExceptionHandler.ThrowException("不存在该入库单： " + dtl.BillID);
                }
               
                if(inStoreBill.BillState != Constant.BillStateDraft)
                {
                    ExceptionHandler.ThrowException("非草稿入库单不能删除明细，入库单： " + dtl.BillID);
                }

                var q = from c in ctx.InStoreBillDtl
                        where c.BillDtlID == dtl.BillDtlID
                        select c;
                var inStoreBillDtl = q.FirstOrDefault();
                if (inStoreBillDtl == null)
                {
                    ExceptionHandler.ThrowException("不存在该入库明细： " + dtl.BillDtlID);
                }
                ctx.Detach(inStoreBillDtl);

                if((inStoreBillDtl.InvoiceDtlTotalAmountTax ??0)>0)
                {
                    ExceptionHandler.ThrowException("该入库明细已经分摊了发票，不能删除： " + dtl.BillDtlID);
                }

                var storeGoods = this.GetStoreGoods(inStoreBillDtl.NewGoodsCode, inStoreBillDtl.SpecificationType);

                if (storeGoods == null)
                {
                    ExceptionHandler.ThrowException(String.Format("库存对象不存在，请联系管理员！物料代码{0}，规格{1}！", inStoreBillDtl.NewGoodsCode, inStoreBillDtl.SpecificationType));
                }

                if (inStoreBillDtl.Quantity > 0)
                {
                    storeGoods.Quantity -= inStoreBillDtl.Quantity;
                    ctx.AddToStoreGoods(storeGoods);
                    ctx.ObjectStateManager.ChangeObjectState(storeGoods, EntityState.Modified);
                }

                ctx.AddToInStoreBillDtl(inStoreBillDtl);
                ctx.ObjectStateManager.ChangeObjectState(inStoreBillDtl, EntityState.Deleted);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }
        }
        #endregion

        #region OutStoreBill
        public List<OutStoreBill> GetOutStoreBills()
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.OutStoreBill
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<OutStoreBill> GetOutStoreBillsByCondition(string condition)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<OutStoreBill>("select * from  dbo.OutStoreBill where  1=1 " + condition + " order by BillID,OutBillDate").ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveOutStoreBills(List<OutStoreBill> list)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region OutStoreBillDtl
        public List<OutStoreBillDtl> GetOutStoreBillDtls()
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.OutStoreBillDtl
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        /// <summary>
        /// 此函数不校验。不存在安全性问题
        /// </summary>
        /// <param name="newGoodsCode"></param>
        /// <returns></returns>
        public decimal GetStoreGoodsQuantity(string newGoodsCode)
        {
            var ctx = Factory.ContextFactory.Create();
            var q = from c in ctx.StoreGoods
                    where c.NewGoodsCode == newGoodsCode
                    select c;
            var sg = q.FirstOrDefault();
            if (sg == null)
                return 0;
            return sg.Quantity;
        }

        public List<OutStoreBillDtl> GetOutStoreBillDtlsByCondition(string condition)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<OutStoreBillDtl>("select * from  dbo.OutStoreBillDtl where  1=1 " + condition + " order by BillID,Idx").ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<ExtendOutStoreBillDtl> GetExtendOutStoreBillDtlsByCondition(string condition)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<ExtendOutStoreBillDtl>("select * from (select dtl.*,m.OutBillDate,m.ProviderName,m.Purpose,m.Department,m.ProjectNo,m.GetName from  dbo.OutStoreBillDtl dtl left outer join dbo.OutStoreBill m on dtl.BillID = m.BillID ) tmp  where 1=1  " + condition + "  order by BillID,OutBillDate").ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveOutStoreBillDtls(List<OutStoreBillDtl> list)
        {
            throw new NotImplementedException();
        }

        public void DeleteOutStoreBillDtl(OutStoreBillDtl dtl)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                //增加校验，如果出库单为草稿可以删除，否则不可以。
                var q1 = from m in ctx.OutStoreBill
                         where m.BillID == dtl.BillID
                         select m;
                var outStoreBill = q1.FirstOrDefault();
                if (outStoreBill == null)
                {
                    ExceptionHandler.ThrowException("不存在该出库单： " + dtl.BillID);
                }

                if (outStoreBill.BillState != Constant.BillStateDraft)
                {
                    ExceptionHandler.ThrowException("非草稿出库单不能删除明细，出库单： " + dtl.BillID);
                }

                var q = from c in ctx.OutStoreBillDtl
                        where c.BillDtlID == dtl.BillDtlID
                        select c;
                var list = q.ToList();
                if (list.Count == 0)
                {
                    ExceptionHandler.ThrowException("不存在该出库明细： " + dtl.BillDtlID);
                }
                ctx.Detach(list[0]);
                ctx.AddToOutStoreBillDtl(list[0]);
                ctx.ObjectStateManager.ChangeObjectState(list[0], EntityState.Deleted);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }
        }

        #endregion

        #region StoreGoods
        public List<StoreGoods> GetStoreGoodsList()
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.StoreGoods
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        private StoreGoods GetStoreGoods(string newGoodsCode, string specificationType)
        {
            var ctx = Factory.ContextFactory.Create();
            List<StoreGoods> list = ctx.ExecuteStoreQuery<StoreGoods>("select * from  dbo.StoreGoods where 1=1 " + String.Format(" and NewGoodsCode = '{0}' and SpecificationType='{1}'", newGoodsCode, specificationType)).ToList();
            if (list.Count == 0)
                return null;
            return list[0];
        }

        public List<StoreGoods> GetStoreGoodsListByCondition(string condition)
        {
            using (var ctx = Factory.ContextFactory.Create())
            {
                return ctx.ExecuteStoreQuery<StoreGoods>("select * from  dbo.StoreGoods where 1=1 " + condition).ToList();
            }
        }

        public List<ExtendStoreGoods> GetExtendStoreGoodsListByCondition(string condition)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                string sql = "select * from ( " +
                             " select CAST(0 as bit) as IsSelect,a.*,b.ChargeID,b.ChargeName,b.GoodsClass,b.GoodsDesc,b.SafeStoreQty, isnull(b.ExtNumeric1,0) as MaxStoreQty , " +
                             " b.StoreLocation,b.ExtVarChar3 as K_ExtVarChar3 from  dbo.StoreGoods  a left join  dbo.GoodsCodeType b " +
                             " on a.NewGoodsCode=b.NewGoodsCode ) temp where (K_ExtVarChar3 is null or K_ExtVarChar3='' or K_ExtVarChar3='1' )  ";
                return ctx.ExecuteStoreQuery<ExtendStoreGoods>(sql + condition).ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<StoreGoods> GetStoreGoodsListByGoodsCodeType(string newGoodsCode)
        {
            SecurityValidate();
            var ctx = Factory.ContextFactory.Create();

            const string sql = "select * from ( " + 
                            " select a.*,b.ChargeID,b.ChargeName,b.GoodsClass,b.GoodsDesc,b.SafeStoreQty, isnull(b.ExtNumeric1,0) as MaxStoreQty , " +
                             " b.StoreLocation,b.ExtVarChar3 as K_ExtVarChar3 from  dbo.StoreGoods  a left join  dbo.GoodsCodeType b " +
                             " on a.NewGoodsCode=b.NewGoodsCode ) temp where (K_ExtVarChar3 is null or K_ExtVarChar3='' or K_ExtVarChar3='1' )  and NewGoodsCode='{0}'  ";
            
            return ctx.ExecuteStoreQuery<StoreGoods>(string.Format(sql, newGoodsCode)).ToList();
        }

        private List<StoreGoods> GetStoreGoodsListByGoodsCodeType2(string newGoodsCode)
        {
            var ctx = Factory.ContextFactory.Create();

            const string sql = "select * from  dbo.StoreGoods  where  NewGoodsCode='{0}'  ";

            return ctx.ExecuteStoreQuery<StoreGoods>(string.Format(sql, newGoodsCode)).ToList();
        }

        public void SaveStoreGoodsList(List<StoreGoods> list)
        {
            throw new NotImplementedException();
        }

        public void ImportStoreGoods(string newGoodsCode)
        {
            SecurityValidate();

            var list = GetGoodsCodeTypesByCondition(string.Format(" and NewGoodsCode = '{0}' and (ExtVarChar3 = '1' or ExtVarChar3 is null or ExtVarChar3 ='' )", newGoodsCode));
            if(list.Count == 0)
            {
                Exceptions.ExceptionHandler.ThrowException(string.Format("新物料代码{0}不存在物料代码库中或者已经作废，请检查！", newGoodsCode));
            }
            var goodsCodeType = list[0];
            var storeGoodsList = GetStoreGoodsListByGoodsCodeType2(newGoodsCode);
            if(storeGoodsList.Count ==0)
            {
                //取最大库存表的编号
                RowIDControllerBaseFactory baseFactory = new RowIDControllerBaseStoreGoodsFactory();
                var controller = baseFactory.GetRowIDController();

                StoreGoods storeGoods = null;

                //定义一个库存对象
                storeGoods = StoreGoods.CreateStoreGoods(controller.GetNextRowID(), 0, 0, 0, 0, 0, 0);
                storeGoods.CREATETIME = DateTime.Now;
                storeGoods.CREATERNAME = ContextUserID;
                storeGoods.ISVALID = Constant.IsValidTrue;
                storeGoods.UPDATERNAME = ContextUserID;
                storeGoods.UPDATETIME = DateTime.Now;
                storeGoods.UnitCode = goodsCodeType.UnitCode;
                storeGoods.UnitName = goodsCodeType.UnitName;
                storeGoods.TaxRate = (decimal)0.17;
                storeGoods.StoreTypeCode = goodsCodeType.StoreTypeCode;
                storeGoods.StoreTypeName = goodsCodeType.StoreTypeName;
                storeGoods.NewGoodsCode = goodsCodeType.NewGoodsCode;
                storeGoods.NewGoodsName = goodsCodeType.NewGoodsName;
                storeGoods.OldGoodsCode = goodsCodeType.OldGoodsCode;
                storeGoods.SpecificationType = "";
                storeGoods.ExtVarChar8 = goodsCodeType.StoreLocation;

                storeGoods.WcfEntityState = EntityState.Added;

                var ctx = Factory.ContextFactory.Create();
                ctx.AddToStoreGoods(storeGoods);
                ctx.ObjectStateManager.ChangeObjectState(storeGoods, storeGoods.WcfEntityState);
                ctx.SaveChanges();
            }
        }
        #endregion

        #region StoreType
        public List<StoreType> GetStoreTypes()
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.StoreType
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveStoreTypes(List<StoreType> list)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();

                foreach (var storeType in list)
                {
                    ctx.AddToStoreType(storeType);
                    ctx.ObjectStateManager.ChangeObjectState(storeType, storeType.WcfEntityState);
                }
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }
        }

        #endregion

        #region Unit
        public List<Unit> GetUnits()
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.Unit
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveUnits(List<Unit> list)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();

                foreach (var unit in list)
                {
                    ctx.AddToUnit(unit);
                    ctx.ObjectStateManager.ChangeObjectState(unit, unit.WcfEntityState);
                }
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }
        }

        #endregion

        #region InStoreType and OutStoreType

        public List<InStoreType> GetInStoreTypes()
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.InStoreType
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveInStoreTypes(List<InStoreType> list)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();

                foreach (var storeType in list)
                {
                    ctx.AddToInStoreType(storeType);
                    ctx.ObjectStateManager.ChangeObjectState(storeType, storeType.WcfEntityState);
                }
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }
        }

        public List<OutStoreType> GetOutStoreTypes()
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.OutStoreType
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<OutStoreType> GetOutStoreTypesInConfig()
        {
            try
            {
                var outInStoreBillTypes = OutInStoreBillTypeFactory.GetOutInStoreBillTypes();
                var list = outInStoreBillTypes.Select(outInStoreBillType => outInStoreBillType.OutStoreCode).ToList();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.OutStoreType
                        where list.Contains(c.OutStoreCode)
                        select c;
                return q.ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SaveOutStoreTypes(List<OutStoreType> list)
        {
            try
            {
                SecurityValidate();
                var ctx = Factory.ContextFactory.Create();

                foreach (var storeType in list)
                {
                    ctx.AddToOutStoreType(storeType);
                    ctx.ObjectStateManager.ChangeObjectState(storeType, storeType.WcfEntityState);
                }
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }
        }

        #endregion

    }
}
